package com.gsp.gspframework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public abstract class ProxyAspect implements Proxy {

    private static final Logger log = LoggerFactory.getLogger(ProxyAspect.class);

    @Override
    public final Object doProxy(ProxyChain proxyChain) throws Throwable {
        Class<?> targetClass = proxyChain.getTargetClass();
        Method targetmethod = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();

        Object result = null;
        begin();
        try {
            if (intercept(targetClass, targetmethod, params)) {
                before(targetClass, targetmethod, params);
                result = proxyChain.doProxyChain();
                after(targetClass, targetmethod, params, result);
            }
        } catch (Throwable throwable) {
            log.error("doProxy error", throwable);
            error(targetClass, targetmethod, params, throwable);
            throw throwable;
        } finally {
            end();
        }

        return result;
    }

    public void begin() {
    }

    public void end() {
    }

    public boolean intercept(Class<?> clz, Method method, Object[] args) {
        return true;
    }

    public void before(Class<?> clz, Method method, Object[] args) throws Throwable {
    }

    public void after(Class<?> clz, Method method, Object[] args, Object result) throws Throwable {
    }

    public void error(Class<?> clz, Method method, Object[] args, Throwable e) {
    }


}
